package com.clh.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clh.seckill.pojo.SeckillOrder;
import com.clh.seckill.mapper.SeckillOrderMapper;
import com.clh.seckill.pojo.User;
import com.clh.seckill.service.ISeckillOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clh.seckill.utils.MD5Util;
import com.clh.seckill.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author clh
 * @since 2021-11-12
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {

    @Autowired
    SeckillOrderMapper seckillOrderMapper;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取秒杀结果！
     * @param user
     * @param goodsId
     * @return orderid 秒杀成功  -1 ：无库存 ，0：排队中
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        if (null!=seckillOrder) return seckillOrder.getOrderId();
        else if (redisTemplate.hasKey("isStockEmpty:"+goodsId)) return -1L;
        else
        return 0L;
    }

    /**
     * 生成秒杀接口地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, long goodsId) {
        //生产随机唯一地址
        String randId = String.valueOf(user.getId()).substring(6);
        String path = MD5Util.md5(UUIDUtil.uuid() + randId);
        //存入redis
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+"goods:"+goodsId,path,60, TimeUnit.SECONDS);
        return path;
    }

    /**
     * 校验秒杀地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public Boolean checkPath(User user, Long goodsId,String path) {
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + "goods:" + goodsId);
        return StringUtils.isEmpty(path)?false:path.equals(redisPath);
    }

    @Override
    public Boolean checkCaptcha(User user, Long goodsId, String captcha) {
        //校验验证码
        Object o = redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        String code = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(code);
    }
}
